import { Injectable, ExecutionContext } from '@nestjs/common';
import { ThrottlerGuard } from '@nestjs/throttler';
import { Request } from 'express';

interface AuthenticatedUser {
  id: number;
  username: string;
  email?: string;
}

@Injectable()
export class CustomThrottlerGuard extends ThrottlerGuard {
  protected generateKey(context: ExecutionContext, suffix: string): string {
    const request = context.switchToHttp().getRequest<Request>();
    
    // 使用 IP + User ID（如果已登录）作为限流键
    const ip = request.ip;
    const user = request['user'] as AuthenticatedUser;
    const userId = user?.id || 'anonymous';
    
    return `${ip}-${userId}-${suffix}`;
  }

  protected async getTracker(req: Request): Promise<string> {
    // 优先使用用户 ID，其次使用 IP
    const user = req['user'] as AuthenticatedUser;
    return user?.id?.toString() || req.ip;
  }
}
